﻿using EntityModels.Normal;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System.Data;


namespace EntityModels.DbContexts
{
    /// <summary>
    /// 存储过程映射
    /// </summary>
    public class ApplicationDbContext : DbContext
    {
        /*存储过程定义
CREATE PROCEDURE FindUserViews 
    @like NVARCHAR(MAX),
    @count INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    SET @count = (SELECT COUNT(*) FROM[AspNetUsers] WHERE UserName like N'%' + @like + N'%')
    SELECT[UserName], [PasswordHash] FROM[AspNetUsers] WHERE UserName like N'%' + @like + N'%'

    SET NOCOUNT OFF;
END
*/
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<UserView>().HasNoKey();
        }


        public async Task<(IEnumerable<UserView> userViews, int count)> GetFromProcedureAsync(string value)
        {
            var like = new SqlParameter
            {
                ParameterName = "like",
                SqlDbType = System.Data.SqlDbType.NVarChar,
                Direction = System.Data.ParameterDirection.Input,
                Value = value
            };
            var outputCount = new SqlParameter
            {
                ParameterName = "count",
                SqlDbType = SqlDbType.Int,
                Direction = ParameterDirection.Output
            };
            string sqlQuery = "Exec [FindUserViews] @like, @count OUTPUT";
            IEnumerable<UserView> userViews = await Set<UserView>().FromSqlRaw(sqlQuery, like, outputCount).ToArrayAsync();
            return (userViews, outputCount.Value as int? ?? default);
        }
    }
}
